#pragma once

#include <iostream>
#include <string>
#include <string.h>

#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Common.hpp"

static const int defaultsocketfd = -1; // 默认套接字描述符
static const int defaultport = 8888;
static const std::string iP = "127.0.0.1";

namespace InitAddrArea
{
    using namespace LogArea;
    class InitAddr
    {
    private:
        //将 Port 从网络字节序转主机字节序, 保证大小端一致
        void PortNetToHost()
        {
            _port = ::ntohs(_addr.sin_port);
        }

        //将 Ip 从网络字节学转主机字节序
        void IpNetToHost()
        {
            char buffer[64];
            const char* ip = ::inet_ntop(AF_INET,&_addr.sin_addr.s_addr,buffer,sizeof(buffer));
            _ip = ip;
        }
    public:
        InitAddr()
        {}
        InitAddr(const struct sockaddr_in& addr):_addr(addr)
        {
            PortNetToHost();
            IpNetToHost();
        }
        InitAddr(const uint16_t port) : _port(port), _ip("")
        {
            _addr.sin_family = AF_INET;
            _addr.sin_port = ::htons(_port);
            _addr.sin_addr.s_addr = INADDR_ANY; // 接受任何ip地址
        }

        struct sockaddr* GetAddr() { return CONV(&_addr); }
        socklen_t Size() { return sizeof(_addr); }
        std::string GetIp() { return _ip; }
        uint16_t GetPort() { return _port; }

        ~InitAddr()
        {
        }

    private:
        uint16_t  _port;
        std::string _ip;
        struct sockaddr_in _addr;
    };
}